package com.mobzilla.service;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PutMethod;

import android.os.AsyncTask;
import android.util.Log;

import com.mobzilla.util.Lock;

/** Used to make aysnc Put requests **/
class HTTPRequestPutAsync extends AsyncTask<String, Void, String> {
	private String url;
	private Lock<String> lock;
	private String content;

	public HTTPRequestPutAsync(String url, Lock<String> l, String content) {
		this.url = url;
		this.lock = l;
		this.content = content;
	}

	@SuppressWarnings("deprecation")
	@Override
	protected String doInBackground(String... params) {

		HttpClient client = new HttpClient();

		PutMethod putMethod = new PutMethod(url);

		putMethod.setRequestBody(content);
		putMethod.setRequestHeader("Content-Type", "application/json");

		try {
			client.executeMethod(putMethod);
			if (!putMethod.getStatusText().equalsIgnoreCase("accepted")) {
				Log.w("Mobzilla", "Error " + putMethod.getStatusText()
						+ " for URL " + url);
			}
			
			lock.setData(putMethod.getStatusText());
		} 
		catch (Exception e) 
		{
			lock.setData(null);
			Log.w("Mobzilla", "Error for URL " + url, e);
		}
		
		lock.setDataSet(true);

		return null;
	}
}
